import React, {useState} from 'react';
import {Input} from 'antd';

const {Search} = Input;

export default function Topic3() {
  const [value, setValue] = useState('');
  const onSearch = (value) => {
    getHighestFreqChar(value)

  }
  const getHighestFreqChar = (value) => {
    if (value) {
      // 通过正则查询字符串中是否存在重复项
      if (value.search(/(.+)(?=.*\1.*)/) < 0) return setValue('')
      const newValue = value.split('')
      // 过滤重复项
      var notRepeat = newValue.filter((item, index, self) => self.indexOf(item) === index);
      // 当重复项只有一个时
      if (notRepeat.length === 1) {
        return setValue(notRepeat[0].key)
      }
      const result = [];
      // 所有重复元素添加进新数组内
      notRepeat.forEach((item, i) => {
        const t = newValue.filter(x => x === item);
        if (t.length > 1) {
          result.push({len: t.length, key: item});
        }
      });
      result.sort((a, b) => b.len - a.len)
      // 当有多个重复项数量一致时
      if (result[0].len === result[1].len) {
        return setValue(result[1].key)
      }
      return setValue(result[0].key)
    }
  }

  const onChange = (event) => {
    console.log(event.target.defaultValue)
  }
  return (
    <div>
      <Search
        placeholder="input search text"
        allowClear
        onChange={onChange}
        defaultValue="aabbccdd"
        enterButton="运行"
        size="large"
        onSearch={onSearch}
      />
      <div>
        重复字符串：{value}
      </div>
    </div>
  )
}
